package com.guicent.geekai.controller;

import com.guicent.geekai.entity.User;
import com.guicent.geekai.service.UserService;
import com.guicent.geekai.util.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 * 登录控制器
 *
 * @author xiaojiang
 * @date 2025/03/14
 */
@RestController
@RequestMapping("/api/auth")
@Api(tags = "登录")
public class LoginController {

    @Autowired
    private UserService userService;

    /**
     * 注册
     *
     * @param account  账户
     * @param password 密码
     * @return {@link R }
     */
    @PostMapping("/login")
    @ApiOperation(value = "登录接口", notes = "登录")
    public R login(@RequestParam String account, @RequestParam String password) {
        boolean success = userService.checkLogin(account, password);
        if (success) {
            return R.ok();
        } else {
            return R.error().message("账号或密码错误");
        }
    }

    /**
     * 登记
     *
     * @param account  账户
     * @param password 密码
     * @return {@link R }
     */
    @PostMapping("/register")
    @ApiOperation(value = "注册接口", notes = "注册")
    public R register(@RequestParam String account, @RequestParam String password) {
        if (userService.existsByAccount(account)) {
            return R.error().message("账号已存在");
        }
        User newUser = new User();
        newUser.setAccount(account);
        newUser.setPassword(password);
        newUser.setCreateTime(LocalDateTime.now());
        try {
            userService.saveUser(newUser);
            return R.ok().message("注册成功");
        } catch (Exception e) {
            return R.error().message(e.getMessage());
        }
    }
}